package edu.xhu;

import java.util.ArrayList;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.AlreadyBookBean;
import com.bean.User;
import com.constant.Constant;
import com.data.LoginLibraryData;
import com.net.ClientError;
import com.net.LoadData;
import com.net.RequestListener;
import com.net.RequestParameter;

import edu.xhu.adapters.MyLibraryAdapter;
import edu.xhu.util.DatabaseAdapter;
import edu.xhu.util.FileManager;
import edu.xhu.view.LoadingDialog;

/**
 * 图书馆
 * @author swerit
 *
 */
public class Library extends Activity{

	private LinearLayout mContainer;
	private TextView mSearch, mIBorrow;
	private LayoutInflater inflater;
	private Button mBtnBack;					//返回按钮
	private TextView title;						//标题
	
	//搜索界面的控件
	private Button mBtnSearch;
	private View searchView;
	private View myLibraryView;
	private EditText searchEditText;
	
	//“我借的书”界面控件
	private EditText userIdEditText, pwdEditText;			//帐号，密码的输入框
	private String userId, password;						//帐号，密码
	private CheckBox rememberMe;							//记住我单选框
	private ListView myBooksListView;						//我借的书籍listview
	private Button mButtonLogin;							//登录按钮
	private LinearLayout loginLayout;						//登录界面
	private LinearLayout myLibraryLayout;					//我的图书馆界面
	private ArrayList<AlreadyBookBean> mAlreadyBook;
	private MyLibraryAdapter adapter;
	
	private DatabaseAdapter dbAdapter;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.library);
		
		initView();
		setLinstener();
		dbAdapter = new DatabaseAdapter(this);
	}
	
	/**
	 * 初始化界面
	 */
	private void initView() {
		mContainer			= (LinearLayout) findViewById(R.id.library_container);
		mSearch				= (TextView) findViewById(R.id.textview_search);
		mIBorrow			= (TextView) findViewById(R.id.textview_i_borrow);
		mBtnBack			= (Button) findViewById(R.id.button_back);
		title				= (TextView) findViewById(R.id.title);
		
		inflater 			= LayoutInflater.from(this);
		//初始化搜书界面控件
		searchView			= inflater.inflate(R.layout.library_search, null);
		mBtnSearch			= (Button) searchView.findViewById(R.id.button_search);
		searchEditText		= (EditText) searchView.findViewById(R.id.edittext_search);
		
		//初始化我借的书界面，登录界面和结果界面
		myLibraryView 		= inflater.inflate(R.layout.library_i_borrow, null);
		myLibraryView.setVisibility(View.GONE);
		userIdEditText		= (EditText) myLibraryView.findViewById(R.id.edittext_userid);
		pwdEditText			= (EditText) myLibraryView.findViewById(R.id.edittext_password);
		rememberMe			= (CheckBox) myLibraryView.findViewById(R.id.remember_me);
		myBooksListView		= (ListView) myLibraryView.findViewById(R.id.listview_mybooks);
		mButtonLogin		= (Button) myLibraryView.findViewById(R.id.button_login);
		loginLayout			= (LinearLayout) myLibraryView.findViewById(R.id.login_library);
		myLibraryLayout		= (LinearLayout) myLibraryView.findViewById(R.id.my_library);

		//userIdEditText.setText("312009070102221");
		//pwdEditText.setText("19900630");
		
		//将两个界面加入到主界面中
		mContainer.addView(searchView);
		mContainer.addView(myLibraryView);
	}
	
	/**
	 * 给控件添加点击事件
	 */
	private void setLinstener(){
		mSearch.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mSearch.setBackgroundResource(R.drawable.btn3_left_hot);
				mIBorrow.setBackgroundResource(R.drawable.btn3_right);
				myLibraryView.setVisibility(View.GONE);
				searchView.setVisibility(View.VISIBLE);
			}
		});
		
		mIBorrow.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mSearch.setBackgroundResource(R.drawable.btn3_left);
				mIBorrow.setBackgroundResource(R.drawable.btn3_right_hot);
				myLibraryView.setVisibility(View.VISIBLE);
				searchView.setVisibility(View.GONE);
				
				if (userId==null && password==null){
					initFrame();
				}
			}
		});
		
		mBtnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
				
				/*Intent intent = new Intent();
				intent.setClass(Library.this,XiHuaActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);*/
			}
		});
		
		mBtnSearch.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String keywords = searchEditText.getText().toString().trim();
				if (keywords == null || keywords.equals("")){
					Animation shake = AnimationUtils.loadAnimation(Library.this, R.anim.shake);
					searchEditText.startAnimation(shake);
					return;
				}
				
				Intent intent = new Intent(Library.this, BookListActivity.class);
				intent.putExtra(BookListActivity.FROM, BookListActivity.FROM_SEARCH);
				intent.putExtra("key_words", keywords);
				startActivity(intent);
			}
		});
		
		mButtonLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				userId		= userIdEditText.getText().toString().trim();
				password	= pwdEditText.getText().toString().trim();
				if (userId == null || userId.equals("")
					|| password == null || password.equals("")){
					Toast.makeText(Library.this, "帐号和密码不能为空", 0).show();
					return;
				}
				
				loginMyLibrary();
			}
		});
		
		myBooksListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(Library.this, WebviewActivity.class);
				intent.putExtra(WebviewActivity.REQUEST_URL, mAlreadyBook.get(position).url);
				intent.putExtra(WebviewActivity.REFERER, mAlreadyBook.get(position).referer);
				startActivity(intent);
			}
		});
	}
	
	private void initFrame(){
		dbAdapter.openDatabase();
		User user = dbAdapter.getAccount(User.LIBRARY);
		dbAdapter.closeDatabase();
		if (user != null){
			userId = user.getUserId();
			password = user.getPassword();
		}
		
		if (userId != null && !userId.equals("")
				&& password != null && !password.equals("")){
			
			userIdEditText.setText(userId);
			pwdEditText.setText(password);
			rememberMe.setChecked(true);
		}
	}
	
	/**
	 * 登录我的图书馆
	 */
	private void loginMyLibrary(){
		mSearch.post(new Runnable() {
			public void run() {
				LoadingDialog.showWindow(Library.this);
			}
		});
		
		RequestParameter parameter = new RequestParameter();
		parameter.add("number", userId);
		parameter.add("passwd", password);
		parameter.add("select", "cert_no");
		parameter.add("returnUrl", "");
		
		LoadData.loadData(Constant.LOGIN_LIBRARY_DATA, parameter, new RequestListener()
		{
			public void onComplete(Object obj) {
				LoginLibraryData data = (LoginLibraryData) obj;
				
				if (data.getRegister()){
					//该用户没有在网上实名认证
					LoadingDialog.dismiss();
					Toast.makeText(Library.this, "请在网上图书馆实名认证之后再使用", Toast.LENGTH_SHORT).show();
					return;
				}
				
				mAlreadyBook = data.getAlreadyBookList();
				adapter = new MyLibraryAdapter(Library.this, data.getCookie(), mAlreadyBook);
				myBooksListView.setAdapter(adapter);
				
				loginLayout.setVisibility(View.GONE);
				myLibraryLayout.setVisibility(View.VISIBLE);
				
				if (rememberMe.isChecked()){
					//登录成功，获取数据之后将登录信息保存在本地
					User user = new User();
					user.setUserId(userId);
					user.setPassword(password);
					user.setPart(User.LIBRARY);
					dbAdapter.openDatabase();
					dbAdapter.saveAccount(user);
					dbAdapter.closeDatabase();
				}
				title.setText("欢迎您：" + data.getUserName());
				
				LoadingDialog.dismiss();
			}

			public void onError(ClientError ed) {
				LoadingDialog.dismiss();
				ErrorShow.showError(Library.this, ed);
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK){
			if (LoadingDialog.isShowing())
				LoadingDialog.dismiss();
			else {
				finish();
				
				/*Intent intent = new Intent();
				intent.setClass(Library.this,XiHuaActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);*/
			}
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}
}
